package com.xunfang.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunfang.portal.model.entity.Book;
import com.xunfang.portal.model.entity.BookCollection;
import com.xunfang.portal.service.BookCollectionService;
import com.xunfang.portal.mapper.BookCollectionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author scott
* @description 针对表【t_book_collection】的数据库操作Service实现
* @createDate 2025-10-24 09:14:26
*/
@Service
public class BookCollectionServiceImpl extends ServiceImpl<BookCollectionMapper, BookCollection>
    implements BookCollectionService{

    @Autowired
    private BookCollectionMapper bookCollectionMapper;

    @Override
    public void addToFavorites(Long bookId, String userId) {

        //往 BookCollection 中添加数据
        BookCollection bookCollection = new BookCollection();
        bookCollection.setBookId(bookId);
        bookCollection.setUserId(Long.parseLong(userId));

        //保存到 BookCollection 表中
        baseMapper.insert(bookCollection);
    }

    @Override
    public Boolean checkFavorite(Long bookId, String userId) {

        //查询 BookCollection
        LambdaQueryWrapper<BookCollection> bookCollectionLambdaQueryWrapper = Wrappers.lambdaQuery(BookCollection.class)
                .eq(BookCollection::getBookId, bookId)
                .eq(BookCollection::getUserId, userId);

        Long count = bookCollectionMapper.selectCount(bookCollectionLambdaQueryWrapper);

        return count>0;
    }

    @Override
    public void removeToFavorite(Long bookId, String userId) {

        //通过userId 和 bookId 删除
        LambdaQueryWrapper<BookCollection> bookCollectionLambdaQueryWrapper = Wrappers.lambdaQuery(BookCollection.class)
                .eq(BookCollection::getBookId, bookId)
                .eq(BookCollection::getUserId, Long.parseLong(userId));

        bookCollectionMapper.delete(bookCollectionLambdaQueryWrapper);

    }

    @Override
    public Page<Book> getMyFavorites(String userId, Integer pageNum, Integer pageSize) {
        Page<Book> page = new Page<>(pageNum, pageSize);
        List<Book> books = bookCollectionMapper.findFavoriteBooksByUserId(Long.valueOf(userId), page);

        //page 对象
        //  封装了 分页的数据    currentPage,pageSize ,records
        //mapper 查询的分页结果  需要给 page 下面的records 进行设置
        page.setRecords(books);
        return page;
    }
}




